<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>检查当前用户信息 - 调试工具</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#409EFF',
                        success: '#67C23A',
                        warning: '#E6A23C',
                        danger: '#F56C6C',
                        info: '#909399'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-shadow {
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            }
            .highlight {
                background-color: #fff9c4;
                padding: 0 2px;
                border-radius: 2px;
            }
        }
    </style>
    <!-- 内联基础图标样式 -->
    <style>
        .icon-success:before { content: '✓'; }
        .icon-warning:before { content: '⚠'; }
        .icon-danger:before { content: '✗'; }
        .icon-info:before { content: 'ℹ'; }
        .icon-user:before { content: '👤'; }
        .icon-key:before { content: '🔑'; }
        .icon-search:before { content: '🔍'; }
        .icon-wrench:before { content: '🔧'; }
        .icon-magic:before { content: '✨'; }
        .icon-user-plus:before { content: '👥'; }
        .icon-trash:before { content: '🗑️'; }
    </style>
</head>
<body class="bg-gray-50 font-inter min-h-screen">
    <div class="container mx-auto px-4 py-10 max-w-4xl">
        <header class="text-center mb-8">
            <h1 class="text-2xl font-bold text-gray-800 mb-2">检查当前用户信息</h1>
            <p class="text-gray-600">查看并分析浏览器localStorage中的登录状态和用户信息</p>
        </header>

        <main>
            <!-- 登录状态概览 -->
            <section class="bg-white rounded-xl shadow-lg p-6 mb-8 card-shadow">
                <h2 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
                <span class="icon-user text-xl mr-2"></span>
                登录状态概览
            </h2>
                
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <p class="text-sm text-gray-500 mb-1">Token 状态</p>
                        <p id="tokenStatus" class="text-lg font-semibold"></p>
                    </div>
                    
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <p class="text-sm text-gray-500 mb-1">用户信息</p>
                        <p id="userInfoStatus" class="text-lg font-semibold"></p>
                    </div>
                    
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <p class="text-sm text-gray-500 mb-1">登录状态</p>
                        <p id="loginStatus" class="text-lg font-semibold"></p>
                    </div>
                </div>
            </section>

            <!-- 用户信息详情 -->
            <section class="bg-white rounded-xl shadow-lg p-6 mb-8 card-shadow">
                <h2 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
                <span class="icon-info text-xl mr-2"></span>
                用户信息详情
            </h2>
                
                <div class="mb-4">
                    <pre id="userInfoContent" class="bg-gray-50 p-4 rounded-lg overflow-x-auto text-sm"></pre>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <h3 class="font-medium text-gray-800 mb-2">角色信息分析</h3>
                        <ul id="roleAnalysis" class="text-sm space-y-1 list-disc list-inside"></ul>
                    </div>
                    
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <h3 class="font-medium text-gray-800 mb-2">用户属性检查</h3>
                        <ul id="userAttributes" class="text-sm space-y-1 list-disc list-inside"></ul>
                    </div>
                </div>
            </section>

            <!-- 问题诊断 -->
            <section class="bg-white rounded-xl shadow-lg p-6 mb-8 card-shadow">
                <h2 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
                <span class="icon-search text-xl mr-2"></span>
                问题诊断
            </h2>
                
                <div id="diagnosisResult" class="space-y-4">
                    <div id="diagnosisLoading" class="text-center py-4">
                        🔄 正在进行问题诊断...
                    </div>
                    <div id="diagnosisIssues" class="hidden space-y-2"></div>
                </div>
            </section>

            <!-- 修复工具 -->
            <section class="bg-white rounded-xl shadow-lg p-6 card-shadow">
                <h2 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
                <span class="icon-wrench text-xl mr-2"></span>
                修复工具
            </h2>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <button id="fixUserInfoBtn" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-all shadow flex items-center justify-center">
                        <span class="icon-magic mr-2"></span>
                        修复用户信息
                    </button>
                    
                    <button id="simulateAdminBtn" class="px-4 py-2 bg-success text-white rounded-lg hover:bg-success/90 transition-all shadow flex items-center justify-center">
                        <span class="icon-user-plus mr-2"></span>
                        设置模拟管理员
                    </button>
                    
                    <button id="createTestTokenBtn" class="px-4 py-2 bg-warning text-white rounded-lg hover:bg-warning/90 transition-all shadow flex items-center justify-center">
                        <span class="icon-key mr-2"></span>
                        创建测试Token
                    </button>
                    
                    <button id="clearAllBtn" class="px-4 py-2 bg-danger text-white rounded-lg hover:bg-danger/90 transition-all shadow flex items-center justify-center">
                        <span class="icon-trash mr-2"></span>
                        清除所有数据
                    </button>
                </div>
            </section>
        </main>

        <footer class="mt-10 text-center text-gray-500 text-sm">
            <p>登录状态调试工具 - 帮助分析并解决用户显示问题</p>
        </footer>
    </div>

    <script>
        // 页面加载时执行检查
        window.addEventListener('load', function() {
            checkUserInfo();
        });

        // 检查用户信息
        function checkUserInfo() {
            // 检查Token
            const token = localStorage.getItem('token');
            const tokenStatusElement = document.getElementById('tokenStatus');
            
            if (token && token !== '') {
                tokenStatusElement.textContent = '存在';
                tokenStatusElement.className = 'text-lg font-semibold text-success';
            } else {
                tokenStatusElement.textContent = '不存在';
                tokenStatusElement.className = 'text-lg font-semibold text-danger';
            }

            // 检查用户信息
            const userInfoStr = localStorage.getItem('userInfo');
            const userInfoStatusElement = document.getElementById('userInfoStatus');
            const userInfoContentElement = document.getElementById('userInfoContent');
            const roleAnalysisElement = document.getElementById('roleAnalysis');
            const userAttributesElement = document.getElementById('userAttributes');
            
            if (userInfoStr && userInfoStr !== '') {
                userInfoStatusElement.textContent = '存在';
                userInfoStatusElement.className = 'text-lg font-semibold text-success';
                
                try {
                    const userInfo = JSON.parse(userInfoStr);
                    userInfoContentElement.textContent = JSON.stringify(userInfo, null, 2);
                    
                    // 分析角色信息
                    let roleAnalysisHTML = '';
                    if (userInfo.roles && Array.isArray(userInfo.roles)) {
                        roleAnalysisHTML += `<li class="text-success">✓ roles字段存在且为数组</li>`;
                        if (userInfo.roles.length > 0) {
                            roleAnalysisHTML += `<li>角色列表: ${userInfo.roles.join(', ')}</li>`;
                        } else {
                            roleAnalysisHTML += `<li class="text-warning">⚠️ 角色数组为空</li>`;
                        }
                    } else if (userInfo.role) {
                        roleAnalysisHTML += `<li class="text-warning">⚠️ 存在role字段但不是roles数组</li>`;
                        roleAnalysisHTML += `<li>当前角色值: ${userInfo.role}</li>`;
                    } else {
                        roleAnalysisHTML += `<li class="text-danger">✗ 未找到角色信息</li>`;
                    }
                    roleAnalysisElement.innerHTML = roleAnalysisHTML;
                    
                    // 分析用户属性
                    let userAttributesHTML = '';
                    const requiredFields = ['username', 'realName', 'avatar', 'roles'];
                    
                    requiredFields.forEach(field => {
                        if (userInfo.hasOwnProperty(field)) {
                            if (userInfo[field] && userInfo[field] !== '') {
                                userAttributesHTML += `<li class="text-success">✓ ${field}: ${userInfo[field]}</li>`;
                            } else {
                                userAttributesHTML += `<li class="text-warning">⚠️ ${field}字段存在但为空</li>`;
                            }
                        } else {
                            userAttributesHTML += `<li class="text-danger">✗ 缺少${field}字段</li>`;
                        }
                    });
                    userAttributesElement.innerHTML = userAttributesHTML;
                    
                } catch (e) {
                    userInfoContentElement.textContent = `解析错误: ${e.message}`;
                    userInfoContentElement.className = 'bg-danger/10 p-4 rounded-lg overflow-x-auto text-sm text-danger';
                    roleAnalysisElement.innerHTML = `<li class="text-danger">✗ 无法解析用户信息</li>`;
                }
            } else {
                userInfoStatusElement.textContent = '不存在';
                userInfoStatusElement.className = 'text-lg font-semibold text-danger';
                userInfoContentElement.textContent = 'localStorage中没有用户信息';
                roleAnalysisElement.innerHTML = `<li class="text-danger">✗ 未找到用户信息</li>`;
                userAttributesElement.innerHTML = `<li class="text-danger">✗ 未找到用户信息</li>`;
            }

            // 检查登录状态
            const loginStatusElement = document.getElementById('loginStatus');
            if (token && token !== '') {
                loginStatusElement.textContent = '已登录';
                loginStatusElement.className = 'text-lg font-semibold text-success';
            } else {
                loginStatusElement.textContent = '未登录';
                loginStatusElement.className = 'text-lg font-semibold text-danger';
            }

            // 进行问题诊断
            diagnoseIssues(token, userInfoStr);
        }

        // 问题诊断
        function diagnoseIssues(token, userInfoStr) {
            const loadingElement = document.getElementById('diagnosisLoading');
            const issuesElement = document.getElementById('diagnosisIssues');
            
            // 隐藏加载提示
            loadingElement.classList.add('hidden');
            issuesElement.classList.remove('hidden');
            issuesElement.innerHTML = '';
            
            let issues = [];
            
            // 检查Token
            if (!token || token === '') {
                issues.push({
                    severity: 'danger',
                    message: '缺少登录Token，系统无法识别用户身份',
                    suggestion: '请先登录系统获取有效的Token'
                });
            }
            
            // 检查用户信息
            if (!userInfoStr || userInfoStr === '') {
                issues.push({
                    severity: 'danger',
                    message: 'localStorage中没有用户信息',
                    suggestion: '需要登录系统或手动创建用户信息'
                });
            } else {
                try {
                    const userInfo = JSON.parse(userInfoStr);
                    
                    // 检查realName字段（显示用户名的关键）
                    if (!userInfo.realName || userInfo.realName === '') {
                        issues.push({
                            severity: 'warning',
                            message: '用户信息中缺少realName字段或该字段为空',
                            suggestion: '这会导致系统显示"未登录"而不是用户名'
                        });
                    }
                    
                    // 检查roles字段
                    if (!userInfo.roles || !Array.isArray(userInfo.roles)) {
                        issues.push({
                            severity: 'warning',
                            message: '用户信息中缺少roles数组字段',
                            suggestion: '这可能会导致角色权限验证失败'
                        });
                    }
                    
                    // 检查avatar字段
                    if (!userInfo.avatar || userInfo.avatar === '') {
                        issues.push({
                            severity: 'info',
                            message: '用户信息中缺少头像信息',
                            suggestion: '系统会使用默认头像'
                        });
                    }
                    
                } catch (e) {
                    issues.push({
                        severity: 'danger',
                        message: `用户信息解析错误: ${e.message}`,
                        suggestion: '可能是JSON格式错误或数据损坏'
                    });
                }
            }
            
            // 显示诊断结果
            if (issues.length > 0) {
                issues.forEach(issue => {
                    const issueElement = document.createElement('div');
                    issueElement.className = `p-4 rounded-lg bg-${issue.severity}/10 border-l-4 border-${issue.severity}`;
                    
                    const iconText = issue.severity === 'danger' ? '✗' : 
                                    issue.severity === 'warning' ? '⚠' : 'ℹ';
                    
                    issueElement.innerHTML = `
                        <div class="flex items-start">
                            <span class="text-${issue.severity} mr-3 mt-1 text-xl">${iconText}</span>
                            <div>
                                <p class="font-medium text-${issue.severity}">${issue.message}</p>
                                <p class="text-sm text-gray-600 mt-1">建议: ${issue.suggestion}</p>
                            </div>
                        </div>
                    `;
                    
                    issuesElement.appendChild(issueElement);
                });
            } else {
                const successElement = document.createElement('div');
                successElement.className = 'p-4 rounded-lg bg-success/10 border-l-4 border-success';
                successElement.innerHTML = `
                        <div class="flex items-start">
                            <span class="text-success mr-3 mt-1 text-xl">✓</span>
                            <div>
                                <p class="font-medium text-success">未发现明显问题</p>
                                <p class="text-sm text-gray-600 mt-1">用户信息和登录状态看起来都正常</p>
                            </div>
                        </div>
                    `;
                issuesElement.appendChild(successElement);
            }
        }

        // 修复用户信息
        document.getElementById('fixUserInfoBtn').addEventListener('click', function() {
            if (confirm('确定要修复用户信息吗？这可能会修改当前的用户数据。')) {
                try {
                    const userInfoStr = localStorage.getItem('userInfo');
                    let userInfo = null;
                    
                    if (userInfoStr) {
                        userInfo = JSON.parse(userInfoStr);
                    } else {
                        userInfo = {};
                    }
                    
                    // 确保必要字段存在
                    if (!userInfo.realName) {
                        userInfo.realName = '管理员';
                    }
                    
                    if (!userInfo.roles || !Array.isArray(userInfo.roles)) {
                        userInfo.roles = ['ADMIN'];
                    }
                    
                    if (!userInfo.username) {
                        userInfo.username = 'admin';
                    }
                    
                    // 确保有头像
                    if (!userInfo.avatar) {
                        // 生成默认头像（简单版本）
                        const char = userInfo.realName.charAt(0);
                        userInfo.avatar = `data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2248%22%20height%3D%2248%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23409EFF%22%2F%3E%3Ctext%20x%3D%2250%25%22%20y%3D%2250%25%22%20font-family%3D%22Arial%22%20font-size%3D%2220%22%20font-weight%3D%22bold%22%20text-anchor%3D%22middle%22%20dy%3D%22.35em%22%20fill%3D%22white%22%3E${encodeURIComponent(char)}%3C%2Ftext%3E%3C%2Fsvg%3E`;
                    }
                    
                    // 保存修复后的用户信息
                    localStorage.setItem('userInfo', JSON.stringify(userInfo));
                    
                    alert('用户信息修复成功！');
                    checkUserInfo(); // 重新检查
                } catch (e) {
                    alert(`修复失败: ${e.message}`);
                }
            }
        });

        // 设置模拟管理员
        document.getElementById('simulateAdminBtn').addEventListener('click', function() {
            if (confirm('确定要设置模拟管理员用户吗？这将覆盖现有用户信息。')) {
                const mockAdminUser = {
                    id: 'admin123',
                    realName: '管理员',
                    username: 'admin',
                    roles: ['ADMIN', 'PRODUCT_MANAGER'],
                    avatar: 'data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2248%22%20height%3D%2248%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23409EFF%22%2F%3E%3Ctext%20x%3D%2250%25%22%20y%3D%2250%25%22%20font-family%3D%22Arial%22%20font-size%3D%2220%22%20font-weight%3D%22bold%22%20text-anchor%3D%22middle%22%20dy%3D%22.35em%22%20fill%3D%22white%22%3E管%3C%2Ftext%3E%3C%2Fsvg%3E'
                };
                
                localStorage.setItem('userInfo', JSON.stringify(mockAdminUser));
                
                // 创建测试Token
                const mockToken = 'mock_admin_token_' + new Date().getTime();
                localStorage.setItem('token', mockToken);
                
                alert('已设置模拟管理员用户！');
                checkUserInfo(); // 重新检查
            }
        });

        // 创建测试Token
        document.getElementById('createTestTokenBtn').addEventListener('click', function() {
            const mockToken = 'mock_test_token_' + new Date().getTime();
            localStorage.setItem('token', mockToken);
            alert('测试Token已创建！');
            checkUserInfo(); // 重新检查
        });

        // 清除所有数据
        document.getElementById('clearAllBtn').addEventListener('click', function() {
            if (confirm('确定要清除所有用户数据吗？这将需要重新登录。')) {
                localStorage.removeItem('token');
                localStorage.removeItem('userInfo');
                localStorage.removeItem('permissions');
                alert('所有用户数据已清除！');
                checkUserInfo(); // 重新检查
            }
        });
    </script>
</body>
</html>